/* EasyWay Game Engine
 * Copyright (C) 2007 Daniele Paggi.
 *  
 * Written by: 2007 Daniele Paggi<dshnt@hotmail.com>
 *   
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; either version 2 of
 * the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Library General Public License for more details.
 * 
 * You should have received a copy of the GNU Library General Public
 * License along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */
package org.easyway.editor.forms.components.extended;

import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;

import org.easyway.annotations.editor.Creator;
import org.easyway.editor.commands.Command;
import org.easyway.editor.forms.EditorCore;
import org.easyway.editor.forms.components.Button;

public class ConstructorButton extends Button {

	private static final long serialVersionUID = -7116748102573722594L;

	GenericAnalyzer analyzer;

	Constructor<?> constructor;

	public ConstructorButton(Constructor con, Annotation paramsAnn[][],
			Class params[], Creator cann) {
		super(null, cann == null ? "create" : cann.value());
		analyzer = new GenericAnalyzer(paramsAnn, params);
		constructor = con;

	}

	@Override public void command() {
		removeAllFromPanel();

		analyzer.scanParameters();

		analyzer.group.addEnable(new Button("new instance", "create") {

			private static final long serialVersionUID = -3263654138922981924L;

			public void command() {
				new Command() {
					// --
					public void creation() {
						newInstance();
						destroy();
					}

					// ---
					public void loop() {
					}

					public void render() {
					}

				};

			}
		});
	}

	private void newInstance() {
		Object parameters[] = analyzer.getFinalParameters();
		try {
			System.out.print("parameters: [ ");
			for (int i = 0; i < parameters.length; ++i)
				System.out.print(parameters[i] + " ");
			System.out.print("]\n");
			Object result = constructor.newInstance(parameters);
			if (result != null) {
				EditorCore.getInstance().setSelected(result);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// ---------------------------
	// ---------------------------

}
